<template>
    <div>
        <div class="i-layout-page-header">
            <PageHeader class="product_tabs" hidden-breadcrumb>
                <div slot="title">
                    <router-link :to="{ path: '/admin/marketing/appointment/appointmentList' }">
                    <Button icon="ios-arrow-back" size="small" class="mr20">返回</Button>
                    </router-link>
                    <span v-text="$route.params.id ? '编辑预约配置' : '添加预约配置'" class="mr20"></span>
                </div>
            </PageHeader>
        </div>
        <Card :bordered="false" dis-hover class="ivu-mt">
            <Form :model="formData" :label-width="150">
                <FormItem label="预约名称：">
                    <Input v-model="title" placeholder="请输入预约名称"></Input>
                </FormItem>
                <FormItem label="分享标题：">
                    <Input v-model="formData.shareTitle" placeholder="请输入分享标题"></Input>
                </FormItem>
                <FormItem prop="shareImage">
                    <div class="custom-label" slot="label">
                    <div>
                        <div>分享图片</div>
                    </div>
                        <div>：</div>
                    </div>
                    <div class="picBox" @click="modalPicTapShare('dan', 'danFrom')">
                    <div class="pictrue" v-if="formData.shareImage">
                        <img v-lazy="formData.shareImage" />
                        <Button 
                        type="text" 
                        icon="ios-close-circle" 
                        class="btndel" 
                        @click.stop="deleteImage('shareImage')"
                        ></Button>
                    </div>
                        <div class="upLoad acea-row row-center-wrapper" v-else>
                            <Icon type="ios-camera-outline" size="26" class="iconfonts" />
                        </div>
                    </div>
                </FormItem>
                <FormItem label="活动描述：">
                    <vue-ueditor-wrap
                        v-model="formData.rule_descr"
                        :key="1"
                        @beforeInit="addCustomDialog"
                        :config="myConfig"
                        style="width: 90%"
                    ></vue-ueditor-wrap>
                 </FormItem>
                <FormItem prop="image">
                    <div class="custom-label" slot="label">
                    <div>
                        <div>底部信息背景</div>
                    </div>
                        <div>：</div>
                    </div>
                    <div class="picBox" @click="modalPicTap('dan', 'danFrom')">
                        <div class="pictrue" v-if="formData.image">
                            <img v-lazy="formData.image" />
                            <Button 
                            type="text" 
                            icon="ios-close-circle" 
                            class="btndel" 
                            @click.stop="deleteImage('image')"
                            ></Button>
                        </div>
                        <div class="upLoad acea-row row-center-wrapper" v-else>
                            <Icon type="ios-camera-outline" size="26" class="iconfonts" />
                        </div>
                    </div>
                </FormItem>
                <!-- 长图最底部改为富文本编辑器 -->
                <FormItem label="长图最底部：">
                    <vue-ueditor-wrap
                        v-model="formData.bottomContent"
                        :key="2"
                        @beforeInit="addCustomDialog"
                        :config="myConfig"
                        style="width: 90%"
                    ></vue-ueditor-wrap>
                </FormItem>
                <FormItem label="活动时间：">
                <DatePicker
                    :value="datetime"
                    :editable="false"
                    type="datetimerange"
                    placeholder="在这个时间内登录发放"
                    @on-change="dateChange"
                ></DatePicker>
                </FormItem>
                <FormItem label="左右边距 (rpx)：">
                    <div class="control-wrapper">
                    <input
                        type="range"
                        class="slider"
                        :min="0"
                        :max="200"
                        :step="1"
                        v-model.number="formData.marginLeftRight"
                    >
                    <input
                        type="number"
                        class="number-input"
                        :min="0"
                        :max="200"
                        :step="1"
                        v-model.number="formData.marginLeftRight"
                        @keyup.enter="normalizeMargin('marginLeftRight')"
                    >
                    <span class="unit">px</span>
                    </div>
                </FormItem>
                <FormItem label="上下边距 (rpx)：">
                    <div class="control-wrapper">
                    <input
                        type="range"
                        class="slider"
                        :min="0"
                        :max="200"
                        :step="5"
                        v-model.number="formData.marginTopBottom"
                    >
                    <input
                        type="number"
                        class="number-input"
                        :min="0"
                        :max="200"
                        :step="5"
                        v-model.number="formData.marginTopBottom"
                        @keyup.enter="normalizeMargin('marginTopBottom')"
                    >
                    <span class="unit">px</span>
                    </div>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="save">立即创建</Button>
                </FormItem>
            </Form>
        </Card>
        <!-- 顶部Banner图片上传弹窗 -->
        <Modal
            v-model="modalPicBanner"
            width="950px"
            scrollable
            footer-hide
            closable
            title="上传顶部Banner图"
            :mask-closable="false"
            :z-index="1"
        >
            <uploadPictures
            :isChoice="isChoice"
            @getPic="getPicBanner"
            v-if="modalPicBanner"
            ></uploadPictures>
        </Modal>
        <!-- 分享图片上传弹窗 -->
        <Modal
            v-model="modalPicshare"
            width="950px"
            scrollable
            footer-hide
            closable
            title="上传分享图"
            :mask-closable="false"
            :z-index="1"
        >
            <uploadPictures
            :isChoice="isChoice"
            @getPic="getPicshare"
            v-if="modalPicshare"
            ></uploadPictures>
        </Modal>
        <!-- 底部背景图片上传弹窗 -->
        <Modal
            v-model="modalPic"
            width="950px"
            scrollable
            footer-hide
            closable
            title="上传底部背景图"
            :mask-closable="false"
            :z-index="1"
        >
            <uploadPictures
            :isChoice="isChoice"
            @getPic="getPic"
            v-if="modalPic"
            ></uploadPictures>
        </Modal>
    </div>
</template>


<script>
import uploadPictures from "@/components/uploadPictures";
import VueUeditorWrap from "vue-ueditor-wrap";
import {
    cformksetApi,
    sformklApi
} from "@/api/marketing";
export default {
    components: {
        uploadPictures,
        VueUeditorWrap,
    },
    data() {
        return {
            title:"",
            begin_time:"",  //开始时间
            end_time:"",  //结束时间
            formData: {
                title:"",
                shareTitle: "",
                bottomImage: "", // 保留原字段，避免数据异常
                shareImage: "",
                image: "",
                rule_descr: "",
                bottomContent: "", // 新增：长图最底部富文本内容
                marginLeftRight: 0, // 左右边距
                marginTopBottom: 0, // 上下边距
            },
            modalPic: false,
            modalPicshare: false,
            modalPicBanner: false,
            isChoice: "",
            tableIndex: 0,
            picTit: "",
            myConfig: {
                autoHeightEnabled: false,
                initialFrameHeight: 500,
                initialFrameWidth: "100%",
                UEDITOR_HOME_URL: "/admin/UEditor/",
                serverUrl: "",
            },
            datetime: [],
        };
    },
    created() {
        if (this.$route.params.id) {
            this.getCouponDetail();
        }
    },
    methods: {
        getCouponDetail(){
            sformklApi(this.$route.params.id)
                .then((res) => { 
                    this.title = res.data.title
                    this.formData = res.data.value
                    
                    // 时间格式化处理
                    const formatTimestamp = (timestamp) => {
                        const time = typeof timestamp === 'number' ? timestamp : Number(timestamp);
                        const date = new Date(time * (time.toString().length === 10 ? 1000 : 1));
                        
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        const hours = String(date.getHours()).padStart(2, '0');
                        const minutes = String(date.getMinutes()).padStart(2, '0');
                        const seconds = String(date.getSeconds()).padStart(2, '0');
                        
                        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    };

                    this.begin_time = formatTimestamp(res.data.begin_time);
                    this.end_time = formatTimestamp(res.data.end_time);
                    this.datetime = [this.begin_time, this.end_time];

                    // 初始化富文本内容（如果是编辑状态）
                    if (!this.formData.bottomContent) {
                        // 兼容旧数据，如有需要可从原图片字段转换
                        this.formData.bottomContent = '';
                    }
                })
                .catch((err) => {
                    this.$Message.error(err.msg);
                });
        },
      
        // 打开顶部Banner图片弹窗
        modalPicTapBanner(tit, picTit, index) {
            this.modalPicBanner = true;
            this.isChoice = tit === "dan" ? "单选" : "多选";
            this.picTit = picTit;
            this.tableIndex = index;
        },
        // 点击分享图片弹窗
        modalPicTapShare(tit, picTit, index) {
            this.modalPicshare = true;
            this.isChoice = tit === "dan" ? "单选" : "多选";
            this.picTit = picTit;
            this.tableIndex = index;
        },
        // 点击底部背景图片弹窗
        modalPicTap(tit, picTit, index) {
            this.modalPic = true;
            this.isChoice = tit === "dan" ? "单选" : "多选";
            this.picTit = picTit;
            this.tableIndex = index;
        },
        // 获取顶部Banner图片
        getPicBanner(pc) {
            if (this.picTit === "danFrom") {
                this.formData.bottomImage = pc.att_dir;
            }
            this.modalPicBanner = false;
        },
        // 获取分享图片
        getPicshare(pc) {
            if (this.picTit === "danFrom") {
                this.formData.shareImage = pc.att_dir;
            }
            this.modalPicshare = false;
        },
        // 获取底部背景图片
        getPic(pc) {
            if (this.picTit === "danFrom") {
                this.formData.image = pc.att_dir;
            }
            this.modalPic = false;
        },
        // 删除图片通用方法
        deleteImage(field) {
            this.formData[field] = "";
        },
        // 时间选择变更
        dateChange(time) {
            this.begin_time = time[0];
            this.end_time = time[1];
        },
        // 添加富文本自定义图片上传弹窗
        addCustomDialog(editorId) {
            window.UE.registerUI(
                "test-dialog",
                function (editor, uiName) {
                let dialog = new window.UE.ui.Dialog({
                    iframeUrl: "/admin/widget.images/index.html?fodder=dialog",
                    editor: editor,
                    name: uiName,
                    title: "上传图片",
                    cssRules: "width:1200px;height:500px;padding:20px;",
                });
                this.dialog = dialog;
                var btn = new window.UE.ui.Button({
                    name: "dialog-button",
                    title: "上传图片",
                    cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
                    onclick: function () {
                    dialog.render();
                    dialog.open();
                    },
                });
                return btn;
                },
            );
        },
        // 确保边距值在有效范围内
        normalizeMargin(field) {
            const min = 0;
            const max = 200;
            const value = Number(this.formData[field]);
            if (isNaN(value)) {
                this.formData[field] = min;
            } else {
                this.formData[field] = Math.min(Math.max(value, min), max);
            }
        },
        // 保存表单
        save() {
            let id = 0;
            if (this.$route.params.id) {
                id = this.$route.params.id;
            }
            this.formData.title = this.title
            // 准备提交数据
            const submitData = {
                title: this.title,
                begin_time: this.begin_time,
                end_time: this.end_time,
                value: this.formData
            };
            
            // 调用保存接口
            cformksetApi(id, submitData)
                .then((res) => {
                    this.$Message.success(res.msg);
                    setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/appointment/appointmentList",
                        });
                    }, 1000);
                })
                .catch((err) => {
                    this.$Message.error(err.msg);
                });
        },
    },
};
</script>

<style scoped>
.info {
    color: #888;
    font-size: 12px;
    margin-top: 4px;
}
.ivu-form >>> .ivu-form-item-label {
    font-weight: 700;
    font-size: 14px !important;
}

.ivu-input-wrapper {
    width: 320px;
}

.ivu-radio-wrapper {
    margin-right: 30px;
    font-size: 14px !important;
}

.ivu-radio-wrapper >>> .ivu-radio {
    margin-right: 10px;
}

.ivu-input-number {
    width: 160px;
}

.ivu-date-picker {
    width: 320px;
}

.ivu-icon-ios-camera-outline {
    width: 120px;
    height: 58px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.02);
    line-height: 58px;
    cursor: pointer;
    vertical-align: middle;
    text-align: center;
}

.upload-list {
    width: 120px;
    height: 58px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    margin-right: 15px;
    display: inline-block;
    position: relative;
    cursor: pointer;
    vertical-align: middle;
}

.upload-list img {
    display: block;
    width: 100%;
    height: 100%;
}

.ivu-icon-ios-close-circle {
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(50%, -50%);
    color: #ff4d4f;
    font-size: 18px;
}
.custom-label {
    display: inline-flex;
    line-height: 1.5;
    align-items: flex-start;
}
.picBox {
    display: inline-block;
    cursor: pointer;
}

.pictrue {
    width: 150px;
    height: 108px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 15px;
    display: inline-block;
    position: relative;
    cursor: pointer;
    overflow: hidden;

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .btndel {
        position: absolute;
        z-index: 9;
        width: 20px !important;
        height: 20px !important;
        right: -10px;
        top: -10px;
        color: #ff4d4f !important;
        background: rgba(255,255,255,0.8);
        border-radius: 50%;
        padding: 0;
    }
}

.control-wrapper {
    width: 500px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.slider {
    flex: 1;
    height: 6px;
    border-radius: 3px;
    -webkit-appearance: none;
    background: #ddd;
    outline: none;
}

.slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #42b983;
    cursor: pointer;
    transition: background 0.3s;
}

.slider::-webkit-slider-thumb:hover {
    background: #359e75;
}

.number-input {
    width: 80px;
    padding: 8px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
    text-align: center;
}

.unit {
    color: #666;
    font-size: 16px;
}
</style>
